package org.example.shiro;

import org.apache.shiro.codec.Base64;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.example.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;


import java.util.LinkedHashMap;
import java.util.Map;

@Configuration //告诉springboot这是一个配置类 == 配置文件
public class ShiroConfig {

    @Value("${shiro.cookie.cipherKey}")
    private String cipherKey;
    @Value("true")
    private boolean rememberMe;

    //创建shiroFilterFactoryBean
    @Bean //给容器中添加组件，以方法名作为组件的id
    //返回类型为组件类型，返回的值：是组件在容器中的实例
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //一：添加Shiro内置过滤器：可以实现权限相关的拦截器
        //常用的过滤器：
        //1.anon:无需认证可以访问 2、authc:必须认证
        //3、user:使用rememberMe的功能可以直接访问  4.perms：必须得到资源权限才可以访问
        //5、该资源必须得到角色权限才可访问

        Map<String,String> filterMap = new LinkedHashMap<String,String>();


        //二：授权过滤器
        //注：当前授权拦截后，shiro会自动跳转到未授权页面
        //perms括号中的内容是权限的值
        filterMap.put("/add","perms[user:add]");
        filterMap.put("/update","perms[user:update]");
        filterMap.put("/*","authc");



        //三：修改调整的登录页面

        //四：设置为授权提示页面
//        shiroFilterFactoryBean.setUnauthorizedUrl("/noAuth");
//        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);

        return shiroFilterFactoryBean;
    }

    @Bean(name="securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm")UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联realm
        securityManager.setRealm(userRealm);
        //记住我
        CookieRememberMeManager rmm = new CookieRememberMeManager();
        if(StringUtils.isNotEmpty(cipherKey)){
            rmm.setCipherKey(Base64.decode(cipherKey));
        }

        securityManager.setRememberMeManager(rmm);
        return securityManager;
    }


    //创建Realm
    @Bean(name="userRealm")
    public UserRealm getRealm(){
        return new UserRealm();
    }
    //用于thymeleaf和shiro标签配合使用
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
